/**
 * @description 路由守卫，目前两种模式：all模式与intelligence模式
 */
import router from '@/router'
import store from '@/store'
import VabProgress from 'nprogress'
import 'nprogress/nprogress.css'
import getPageTitle from '@/utils/pageTitle'
import { authentication, loginInterception, progressBar, recordRoute, routesWhiteList } from '@/config'

VabProgress.configure({
  easing: 'ease',
  speed: 500,
  trickleSpeed: 200,
  showSpinner: false,
})
// 需要校验权限的路径后缀
const pathSuffix = ['add', 'edit', 'detail']

router.beforeResolve(async (to, from, next) => {
  if (progressBar) VabProgress.start()
  let hasToken = store.getters['user/accessToken']
  if (!loginInterception) hasToken = true

  if (hasToken) {
    // 已登录状态
    if (to.path === '/login') {
      next({
        path: '/',
      })
      if (progressBar) VabProgress.done()
    } else {
      const hasPermissions = store.getters['user/permissions']
      if (hasPermissions && hasPermissions.length > 0) {
        // 校验路径
        let toPath = to.path
        let checkPath = toPath.substring(toPath.lastIndexOf('/') + 1, toPath.length)
        if (pathSuffix.includes(checkPath)) {
          if (hasPermissions.includes('*') || hasPermissions.includes(to.meta.permissions)) {
            next()
          } else {
            next('/401')
          }
        } else {
          next()
        }
      } else {
        try {
          //获取用户信息
          let permissions = await store.dispatch('user/getUserInfo')
          // 设置路由
          let accessRoutes = await store.dispatch('routes/setRoutes', permissions)
          router.addRoutes(accessRoutes)
          next({
            ...to,
            replace: true,
          })
        } catch {
          await store.dispatch('user/resetAccessToken')
          if (progressBar) VabProgress.done()
        }
      }
    }
  } else {
    // 未登录状态
    if (routesWhiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      if (recordRoute) {
        next(`/login?redirect=${to.path}`)
      } else {
        next('/login')
      }
      if (progressBar) VabProgress.done()
    }
  }
  document.title = getPageTitle(to.meta.title)
})

router.afterEach(() => {
  if (progressBar) VabProgress.done()
})
